<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>compile</h2>
      <p>a: {{ a }}</p>
      <p>b: {{ b }}</p>
    </div>

    <script>
      const data = {
        a: 3,
        b: 4,
      };

      const compile = (node) => {
        // node.children可以得到这个元素的所有的子节点
        // console.log([...node.children]);
        const children = [...node.children];
        // 用正则去匹配是否有双大括号
        const reg = /\{\{(.*)\}\}/;

        children.forEach((child) => {
          // 检查每个子元素里面是否有双大括号，并且做替换
          if (reg.test(child.textContent)) {
            // 匹配到了以后，看双大括号里面的变量是什么，用data的属性去替换
            child.innerHTML = data[RegExp.$1.trim()];
          }
        });
      };

      compile(document.querySelector("#app"));
    </script>
  </body>
</html>
